import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test {
    public static void main(String[] args) throws SQLException {
        //创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/students?characterEncoding=utf8&uesSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        //连接数据库
        Connection connection = dataSource.getConnection();

        //构建sql语句
//        String sql = "insert into student(name, age) values(?, ?)";
//        PreparedStatement statement = connection.prepareStatement(sql);
//        statement.setString(1, "陈三牛");
//        statement.setInt(2, 19);

//        String sql = "delete from student where id = ?";
//        PreparedStatement statement = connection.prepareStatement(sql);
//        statement.setInt(1, 1);
        //执行sql

//        String sql = "update student set name = ? where name = ?";
//        PreparedStatement statement = connection.prepareStatement(sql);
//        statement.setString(1, "陈四牛");
//        statement.setString(2, "陈牛牛");
//        int n = statement.executeUpdate();


        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet results = statement.executeQuery();
        while(results.next()) {
            int id = results.getInt("id");
            String name = results.getString("name");
            int age = results.getInt("age");
            System.out.println("id:" + id + " name:" + name + " age:" + age);
        }
        //释放资源
        statement.close();
        connection.close();
    }
}
